

import { _decorator, Component, Node, Label, math, Sprite } from 'cc';
import { Msg } from '../../util/msg';
import { utils } from '../../util/util';
import { PostMessageHandler } from "../../util/postMessageHandler";
const { ccclass, property } = _decorator;
declare var window: Window;
@ccclass('UILoading')
export class UILoading extends Component {

    @property(Label)
    txtLoading: Label | undefined;

    @property(Sprite)
    img_loading_bar: Sprite | undefined;

    @property({
        type: String,
        displayName: "loaded_event_name",
        tooltip: "res加载结束事件名",
    })
    loaded_event_name ="msg_res_loaded";

    _percent = 0;
    _realPercent = 0;
    waitList: Record<number, ILoadMsg> = {};
    viewNode: Node | undefined;

    count = 0;
    wait_count = 0;
    current_msg = '';

    isLoading = false;
    start () {
        Msg.on('msg_loading', this.onWaitList.bind(this));
        this.viewNode = this.node.children[0];
        //设置层级为最高
        this.node.setSiblingIndex(9999);

        console.log("初始化loading")
        PostMessageHandler.Instance.postMessage("gameLoadingStart", {
            loading: "loading"
        });

        window["loading"] = this;
    }

    onWaitList (data: ILoadMsg) {
        console.log(data,"data")
        this.waitList[data.id] = data;
        this.isLoading = true;
        this.viewNode!.active = true;
        this._percent = 0;
    }

    update (deltaTime: number) {
        if (!this.isLoading) return;

        this.calculateLoading();
        //lerp是线性插值，这里是让进度条的值趋近于真实值
        this._percent = math.lerp(this._percent, this._realPercent, deltaTime);
        this.txtLoading!.string = this.current_msg;
        this.img_loading_bar!.fillRange = this._percent;
        if (this._percent >= 0.99&& this._realPercent ==1) {
            this.onLoadFinished();
        }

    }

    onLoadFinished () {
        console.log("初始化loading完成")
        Msg.emit(this.loaded_event_name);
        utils.delay(() => {
            this.isLoading = false;
            this.viewNode!.active = false;
        }, 0.1);

    }

    calculateLoading () {
        this.count = 0;
        this.wait_count = 0;
        //this.current_msg = '';
        for (let k in this.waitList) {
            const waitMsg = this.waitList[k];
            this.count += waitMsg.count;
            this.wait_count += waitMsg.wait_count;
            /*
            if (this.wait_count > 0) {
                this.current_msg = `${waitMsg.action} ${waitMsg.current}`;
            }
            */
        }
        this._realPercent = (this.count - this.wait_count) / this.count;
    }

}

export interface ILoadMsg {
    id: number,
    action: string,
    current: string,
    wait_count: number,
    count: number,
}
